#include <Starter.hpp>


int Starter::start(){

	Config *config = Config::instance();

	/* Create TCP/IP-Client and initiate a new connection */
	TCPClient tcpClient(config->isIPv6Flag());
	TCPConnection *tcpConnection;
	tcpConnection = tcpClient.openConnection(config->getPort(), config->getAddress());

	/* Check if connection was established successfully */
	if(tcpConnection==0){

		return CONNECTION_REFUSED;

	}

	tcpConnection->setSendFlags(MSG_NOSIGNAL);
	tcpConnection->setRecvFlags(MSG_WAITALL);


	ReceiveThread receiveThread(tcpConnection);

	unlink(config->getInputFile().c_str());
	if((mkfifo(config->getInputFile().c_str(), 0777)) == -1){
		fprintf(stderr, "FIFO fail\n");
	    exit(0);
	}

	std::string inputString;

	while(true){

		std::ifstream ifs(config->getInputFile().c_str());
		std::getline(ifs,inputString);
		inputString.append(" ");

		std::cout << inputString << std::endl;

		/* Transmit data */
		if(tcpConnection->sendData((void*)inputString.c_str(), inputString.length()+1) <= 0){
			exit(0);
		}

	}

	return NO_ERROR;

}

